/**
 * 
 */
package com.csair.youth.web.action;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.csair.youth.database.Role;
import com.csair.youth.service.impl.PermissionServiceImpl;
import com.csair.youth.service.impl.RoleServiceImpl;

/**
 * @author mickey
 *
 */
public class RoleEditAction extends _BaseAction {
	private Role item;
	private RoleServiceImpl service;
	private PermissionServiceImpl permissionService;

	private List permissions;
	private List curPermissions;
	private String pSelect;
	
	public List getPermissions() {
		return permissions;
	}
	public void setPermissions(List permissions) {
		this.permissions = permissions;
	}
	public List getCurPermissions() {
		return curPermissions;
	}
	public void setCurPermissions(List curPermissions) {
		this.curPermissions = curPermissions;
	}
	
	public RoleServiceImpl getService() {
		return service;
	}
	public void setService(RoleServiceImpl service) {
		this.service = service;
	}
	
	public void setPermissionService(PermissionServiceImpl permissionService) {
		this.permissionService = permissionService;
	}
	
	public Role getItem() {
		return item;
	}
	public void setItem(Role item) {
		this.item = item;
	}

	public String getPSelect() {
		return pSelect;
	}
	public void setPSelect(String pSelect) {
		this.pSelect = pSelect;
	}
	
	public String execute(){
		permissions = permissionService.getAllPermissions();
		if(item != null && !StringUtils.isEmpty(item.getId())){
			//从数据库获取...
			item = service.getRole(item.getId());
			curPermissions = permissionService.getPermissionsByRoleId(item.getId());
		}
		else item = new Role();
		return SUCCESS;
	}
	
	public String save(){
		if(item == null) {
			this.setMessage("角色对象为空.");
			return INPUT;
		}
		if(!validInput(item)) return INPUT;
		service.saveRole(item);
		//保存和权限的对应关系
		service.deleteRoleOldPermissions(item.getId());
		service.saveRolePermissions(item.getId(), pSelect.split(";"));
		this.setMessage("已成功保存角色.");
		return execute();
	}
	
	private boolean validInput(Role item){
		if(item == null) return false;
		boolean allValid = true;
		StringBuffer msgBf = new StringBuffer();
		String name = item.getName();
		if(StringUtils.isEmpty(name) || StringUtils.length(name)> 25){
			msgBf.append("角色名不能为空且必须在25个字符内<br/>");
			allValid = false;
		}
		String desc = item.getDescription();
		if(!StringUtils.isEmpty(desc) && StringUtils.length(desc)> 120){
			msgBf.append("角色描述必须在120个字符内<br/>");
			allValid = false;
		}
		this.setMessage(msgBf.toString());
		return allValid;
	}
}
